<?php

namespace app\admin\controller\dbusercare;

use app\common\controller\Backend;
use app\common\library\Token;
use fast\Random;
use think\Db;
use think\Exception;
use think\Hook;
use think\Validate;

/**
 * 医务管理
 *
 * @icon fa fa-user
 */
class Dbusercare extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,account,name';
    protected $multiFields = "state,attestation";

    /**
     * @var \app\admin\model\DbUsercare
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('DbUsercare');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where('status','1')
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->heading_img = $v->heading_img ? cdnurl($v->heading_img, true) : letter_avatar($v->name);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    if (!Validate::is($params['pwd'], "/^[A-Za-z0-9]{6,20}$/")) {
                        exception(__("The password is a combination of 6-20 letters or numbers"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['pwd'] = md5(md5($params['pwd']) . $params['salt']);
                    $result = $this->model->validate('DbUsercare.add')->save($params);
                    if ($result === false) {
                        exception($this->model->getError());
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    if ($params['pwd']) {
                        if (!Validate::is($params['pwd'], "/^[A-Za-z0-9]{6,20}$/")) {
                            exception(__("The password is a combination of 6-20 letters or numbers"));
                        }
                        $params['salt'] = Random::alnum();
                        $params['pwd'] = md5(md5($params['pwd']) . $params['salt']);
                    } else {
                        unset($params['pwd'], $params['salt']);
                    }
                    $result = $row->validate('DbUsercare.edit')->save($params);
                    if ($result === false) {
                        exception($row->getError());
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $usercare = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$usercare) {
            $this->error(__('No Results were found'));
        }
        Db::startTrans();
        try {
            // 删除会员
            $this->model->save(['status'=>0],['id'=>$ids]);
            // 删除会员指定的所有Token
            Token::clear($ids);
            Hook::listen("user_delete_successed", $usercare);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
        $this->success();
    }

}
